/**
 * Created by wengca on 2017/10/23 0023.
 */
var rp = require('request-promise');
var qs = require('querystring');
var path = require("path");
var fs = require('fs');
var dirPath = path.join(__dirname, "../orderfile");
const WebSocket = require('ws');
const network = require('network');
var ProtoBuf = require("protobufjs");
var gamePro = ProtoBuf.loadSync("../common/game.proto");
var conf = require("./config.json");
var utils = require("./utils");

class Request {
    constructor() {
    }
    /**
     * @param url
     * @param obj
     * @returns {Promise.<*>}
     * @constructor
     */
    async RequestPostFom(url, obj,headers) {
        try {
            let result = await  rp.post(url,{form:obj,headers,headers});
            return result
        }catch (err) {
            console.error(err);
            return {code: 500}
        }
    }

    async RequestPost(url, obj,headers) {
        try {
            let options = {
                method: 'POST',
                url: url,
                timeout: 3000,
                body: obj,
                headers: {
                    "content-type": "application/json",
                },
                json: true // Automatically stringifies the body to JSON
            };
            if (headers){
                options.headers = headers
            }
            let result = await  rp.post(options);
            return result
        }
        catch (err) {
            console.error(err);
            return {code: 500}
        }
    }
    async RequestPosturlencoded(url, obj,headers) {
        try {
            let options = {
                method: 'POST',
                url: url,
                timeout: 3000,
                form: obj,
                headers: {
                    "content-type": "application/x-www-form-urlencoded",
                }
            };
            let result = await  rp.post(options);
            return result
        }
        catch (err) {
            console.error(err);
            return {code: 500}
        }
    }
    /**
     * get获取到服务器信息
     * @param url
     * @param obj
     * @returns {Promise.<*>}
     * @constructor
     */
    async RequestGet(url,obj,headers) {
        try {
            url += qs.stringify(obj)
            console.log("url is",url,obj)
            let options = {
                method: 'GET',
                url: url,
                timeout: 5000,
                body: JSON.stringify(obj),
                // headers: {
                //     "content-type": "application/json",
                // }
            };
            if (headers){
                options.headers = headers
            }
            let result = await rp.get(options);
            return result
        }
        catch (err) {
            console.error("RequestGet err", url, err);
            return {code: 500}
        }
    }

    async RequestDown(url,obj,headers) {
        try {
            url += qs.stringify(obj)
            console.log("url is", url)
            let options = {
                method: 'GEt',
                url: url,
                timeout: 3000,
                body: JSON.stringify(obj),
                headers: {
                    "content-type": "application/json",
                }
            };
            if (headers) {
                options.headers = headers
            }
            let stream = fs.createWriteStream(path.join(dirPath, "order.xls"));
            // console.log("stream",stream)
            let result = await rp.get(options).pipe(stream);
            return ({code: 200,result})
        }
        catch (err) {
            console.log("RequestGet err", url, err);
            return {code: 500}
        }
    }

    async wsClient(PId,obj,cb){
        try {

            var client = new WebSocket('ws://'+ conf.wsUrl)
            client.onerror = ()=>{
                console.log("webSocket error !!");
                return cb({code:500})
            };
            const msgName = utils.getProBuffById(PId)
            const textMessage = gamePro.lookupType(msgName);
            const payload = obj;
            let errMsg = textMessage.verify(payload);
            if (errMsg) throw Error(errMsg);

            let message = textMessage.create(payload);
            let bufferArray = textMessage.encode(message).finish();

            let bufPID = Buffer.allocUnsafe(4);
            bufPID.writeUInt32BE(PId);
            let totalLength = bufferArray.length + bufPID.length
            const bufSend = Buffer.concat([bufPID, bufferArray], totalLength);
            var UserInfo;
            let retCode = 0
            client.onopen = function () {
                client.send(bufSend);//向后台发送数据
             };

            client.onmessage = (buffer) =>{
                const msgNameRes = utils.getProBuffById(20004)
                const textMessageRes = gamePro.lookupType(msgNameRes);
                let encodeBuff = buffer.data.slice(4,buffer.data.length)
                var answerInfo = textMessageRes.decode(encodeBuff);

                if(answerInfo.unErrCode){
                    retCode =answerInfo.unErrCode
                }

                console.log("answerInfo is ",encodeBuff,answerInfo)
                console.log("PId is ",PId,answerInfo.unErrCode,PId == 20005 && answerInfo.unErrCode >1)
                if (PId == 20005 && answerInfo.unErrCode >1 ){
                    const msgUserInfoRes = utils.getProBuffById(10009)
                    const textMessageUserRes = gamePro.lookupType(msgUserInfoRes);
                    let encodeUserBuff = buffer.data.slice(4,buffer.data.length)
                    UserInfo = textMessageUserRes.decode(encodeUserBuff);
                    console.log("UserInfo",UserInfo)
                    client.close()
                    console.log("通知成功1")
                    return cb({code:200,msg:"通知成功",info:retCode,UserInfo:UserInfo});
                }else if (PId !== 20005 ) {
                    client.close()
                    console.log("通知成功2")
                    return cb({code:200,msg:"通知成功",info:retCode});
                }

                //return cb({code:200,msg:"通知成功",info:retCode,UserInfo:UserInfo});
            }



            client.onclose = ()=>{
                console.log('webSocket断开连接')
                client.close()

                // cb({code:500});
            }

        }catch (e) {
            console.error("xxxx",e)
            cb({code:500});
        }
    }
}

module.exports = new Request();